using System;
using System.Windows.Forms;



namespace ScriptEase.Shell.Controls
{
    public partial class ExceptionDialog2 : Form
    {
        public ExceptionDialog2(Exception ex, string titleMessage)
        {
            InitializeComponent();
            _exception = ex;
            this.textTitleMessage.Text = titleMessage;
            this.linkCallStack.Visible = true;
            this.linkInnerException.Visible = (ex.InnerException != null);
            this.txtMessage.Text = ex.GetType() + Environment.NewLine +Environment.NewLine + replaceCrLf(ex.Message);
            this.TopMost = true;

            Trace.Default.Error(titleMessage, ex);
            if (ex.InnerException != null) Trace.Default.Error("InnerException", ex.InnerException);
        }

        private readonly Exception _exception;


        private bool DisplayStackTrace
        {
            get { return _mDisplayStackTrace; }
            set
            {
                _mDisplayStackTrace = value;
                if (value) {
                    this.txtMessage.Text = replaceCrLf(_exception.StackTrace);
                    this.linkCallStack.Text = "FilterString";
                }
                else {
                    this.txtMessage.Text = replaceCrLf(_exception.Message);
                    this.linkCallStack.Text = "StackTrace";
                }
            }
        }

        private bool _mDisplayStackTrace;


        private void linkInnerExceptionLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExceptionDialog2 innerExceptionDialog = new ExceptionDialog2(_exception.InnerException, "Inner exception: " + _exception.InnerException.GetType().Name);
            innerExceptionDialog.Show();
        }


        private void cmdOkClick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void linkCallStackLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.DisplayStackTrace = !this.DisplayStackTrace;
        }

        private string replaceCrLf(string text)
        {
            text = text.Replace("\r\n", Environment.NewLine);
            text = text.Replace("\n", Environment.NewLine);
            return text;
        }
    }
}